package TwoSeach;

import org.junit.Test;

/**
 * @BelongsProject: SeniorArchitect-LeetCode
 * @BelongsPackage: TwoSeach
 * @Author: zhuangxiaoyan
 * @CreateTime: 2023-11-04  09:52
 * @Description: TODO
 * @Version: 1.0
 */
public class 搜索插入位置35 {

    // 并返回其索引
    public int searchInsert(int[] nums, int target) {
        if (nums.length == 0) {
            return -1;
        }
        if (nums[0] > target) {
            return 0;
        }
        if (nums[nums.length - 1] < target) {
            return nums.length;
        }
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = (left + right) >> 1;
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] > target) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return left;
    }

    public int searchInsert2(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int mid = (left + right) >> 1;
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] > target) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return left;
    }

    @Test
    public void test() {
        int i = searchInsert2(new int[]{1, 3, 5, 6}, 2);
        System.out.println(i);
    }
}
